<script setup>
import { ref } from 'vue'
import { userUpdatePasswordService } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores'
const formRef = ref()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

const validateDifferent = (rule, value, callback) => {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

const validateSamePassword = (rule, value, callback) => {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}

const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' },
    { validator: validateDifferent, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度为6-15位', trigger: 'blur' },
    { validator: validateSamePassword, trigger: 'blur' }
  ]
}

const userStore = useUserStore()
const handleSubmit = async () => {
  // 预校验
  await formRef.value.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success('重置密码成功')
  // 密码修改成功后要重新登录
  // 清除本地token
  userStore.removeToken()
  // 清除本地数据
  userStore.setUser({})

  // 强制刷新
  location.reload()
}

const handleReset = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <page-container title="重置密码">
    <el-row>
      <el-col :span="12">
        <el-form
          :model="pwdForm"
          :rules="rules"
          ref="formRef"
          label-width="100px"
        >
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="pwdForm.old_pwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="pwdForm.new_pwd"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input v-model="pwdForm.re_pwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">修改密码</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </page-container>
</template>

<style>
/* 样式可以根据需要自行调整 */
</style>
